package com.llap.exp190929.service;

import com.llap.exp190929.entity.Product;
import com.llap.exp190929.entity.Sale;
import com.llap.exp190929.repository.SaleRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class SaleService {
    private SaleRepository saleRepository;
    private ProductService productService;

    public Sale findSale(int id) {
        return saleRepository.findById(id).orElse(null);
    }

    public Page<Sale> findSales(int page, int pageSize, String sortBy) {
        return saleRepository.findAll(PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, sortBy)));
    }

    public Page<Sale> findSales(int page, int pageSize) {
        return findSales(page, pageSize, "id");
    }

    @Transactional
    public Sale addSale(Sale sale) {
        if (sale.getId() != null) return null;
        Product product = productService.findProduct(sale.getProduct().getId());
        if (sale.getQuantity() > product.getQuantity()) return null;
        product.setQuantity(product.getQuantity() - sale.getQuantity());
        productService.updateProduct(product);
        return saleRepository.save(sale);
    }

    @Transactional
    public Sale updateSale(Sale sale) {
        if (sale.getId() == null) return null;
        return saleRepository.save(sale);
    }

    @Transactional
    public void deleteSale(int id) {
        saleRepository.deleteById(id);
    }
}
